/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json.spi.supports.atomic;

import com.swapper.json.*;

import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * The {@link AtomicIntegerArray} wrapper factory.
 */
public enum AtomicIntegerArrayWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @SuppressWarnings("unchecked")
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    return type == AtomicIntegerArray.class ? (JsonWrapper<T>) Wrapper.INSTANCE : null;
  }

  public enum Wrapper implements JsonWrapper<AtomicIntegerArray> {
    INSTANCE;

    @SuppressWarnings("all")
    @Override
    public JsonValue wrap(AtomicIntegerArray value) {
      if (value == null) {
        return JsonValue.NULL;
      }
      int length = Array.getLength(value);
      List<JsonValue> values = new ArrayList<>(length);
      for (int i = 0; i < length; ++i) {
        values.add(JsonNumber.valueOf(value.get(i)));
      }
      return new JsonArray(values);
    }

    @Override
    public AtomicIntegerArray unwrap(JsonValue value) {
      if (JsonValue.NULL.equals(value)) {
        return null;
      }
      JsonArray jsonArray = value.toJsonArray();
      int length = jsonArray.size();
      AtomicIntegerArray array = new AtomicIntegerArray(length);
      for (int i = 0; i < length; ++i) {
        array.set(i, jsonArray.get(i).toInteger());
      }
      return array;
    }
  }
}
